//
//  InvitationMessageViewController.m
//  nonghubao
//
//  Created by 王 文彬 on 13-10-24.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "InvitationMessageViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Contact.h"
#import "JSONRequest.h"
#import <MessageUI/MessageUI.h>

@interface InvitationMessageViewController ()
{
    UITextView* _askMessageTextView;
    UILabel*    _askMessageInputCounterLabel;
    
    UITextView* _smsMessageTipTextView;
//    UITextView* _smsMessageTextView;
    
    BOOL _hasSMSFriends;   //是否有短信好友（未注册用户)。true=有/false=无
    NSMutableArray* _smsFriends;  //需要短信邀请的好友名单
    
    BOOL _onBackButtonEventWhenViewDidAppear;  //在视图显示完后，是否触发返回按钮的事件。true=是。用于短信发送后，短信窗口dismiss后，本VC是否需要弹出。
}

@end

@implementation InvitationMessageViewController

@synthesize contactsToInvite = _contactsToInvite;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT)];
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height + 50);
    self.view = scrollView;
    self.title = _L(@"vc_title_104");
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *sendButton = [Helper buttonWithStyle:ButtonStyleNavigationSend];
    [sendButton addTarget:self action:@selector(sendButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;


    _askMessageTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, _SYS_FRAME_WIDTH - 10 - 10, 80)];
    _askMessageTextView.font = _SYS_FONT_003;
    _askMessageTextView.textColor = _SYS_COLOR_003;
    _askMessageTextView.layer.cornerRadius = 4;
    _askMessageTextView.layer.borderColor = [_SYS_COLOR_003 CGColor];
    _askMessageTextView.layer.borderWidth = 1;
    _askMessageTextView.delegate = (id)self;
    [_askMessageTextView becomeFirstResponder];
    [self.view addSubview:_askMessageTextView];
    
    
    _askMessageInputCounterLabel = [[UILabel alloc] initWithFrame:CGRectMake(_askMessageTextView.frame.size.width - 110, _askMessageTextView.frame.size.height - 20, 110, 20)];
    _askMessageInputCounterLabel.text = [NSString stringWithFormat:_L(@"tpl_49"), 50];
    _askMessageInputCounterLabel.font = _SYS_FONT_002;
    _askMessageInputCounterLabel.textColor = _SYS_COLOR_003;
    [_askMessageTextView addSubview:_askMessageInputCounterLabel];
    

    //如果有未注册用户，才显示短信框
    if (_hasSMSFriends) {

        //组合由上一个VC传过来的邀请人组数中的前三个人名
        NSMutableArray* tipNames = [[NSMutableArray alloc] init];
        for (int i = 0; i < _smsFriends.count && i < 3; i++) {
            
            Contact* contact = (Contact *) _contactsToInvite[i];
            [tipNames addObject:contact.name];
        }
        
        NSString*  content = [NSString stringWithFormat:_L(@"tpl_48"), [tipNames componentsJoinedByString:@","], _smsFriends.count, _L(@"vc_title_001")];
        //    CGSize size = [content sizeWithFont:_SYS_FONT_002 constrainedToSize: CGSizeMake(280.0f, 200.0f) lineBreakMode:UILineBreakModeWordWrap];
        _smsMessageTipTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, _askMessageTextView.frame.origin.y + _askMessageTextView.frame.size.height, _SYS_FRAME_WIDTH - 10 - 10, 40)];
        _smsMessageTipTextView.font = _SYS_FONT_002;
        _smsMessageTipTextView.text = content;
        _smsMessageTipTextView.editable = false;
        _smsMessageTipTextView.scrollEnabled = false;
        _smsMessageTipTextView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_smsMessageTipTextView];
//
//        
//        _smsMessageTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, _smsMessageTipTextView.frame.origin.y + _smsMessageTipTextView.frame.size.height, _SYS_FRAME_WIDTH - 10 - 10, 80)];
//        _smsMessageTextView.font = _SYS_FONT_003;
//        _smsMessageTextView.textColor = _SYS_COLOR_003;
//        _smsMessageTextView.layer.cornerRadius = 4;
//        _smsMessageTextView.layer.borderColor = [_SYS_COLOR_003 CGColor];
//        _smsMessageTextView.layer.borderWidth = 1;
//        _smsMessageTextView.text = _L(@"tpl_00");
//        [self.view addSubview:_smsMessageTextView];
    }

}


- (void)setContactsToInvite:(NSArray *)contacts
{
    _contactsToInvite = contacts;

    if (_smsFriends == Nil) {
        
        _smsFriends = [[NSMutableArray alloc] init];
    }
    
    for (Contact* contact in _contactsToInvite) {
NSLog(@"....%@ %@ %i", contact.name, contact.mobile, contact.status);
        //如果是未注册（status=false）
        if (contact.status == false) {
            
            _hasSMSFriends = true;
            [_smsFriends addObject:contact];
        }
    }
    
    NSLog(@"%i %@", _hasSMSFriends, _smsFriends);
}


- (void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:animated];
    if (_onBackButtonEventWhenViewDidAppear) {
        
        [self.navigationController dismissModalViewControllerAnimated:false];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 返回按钮事件

- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:true];
}


///////////////////////////////////
#pragma mark - 发送按钮事件 及 处理逻辑

- (void)sendButtonEvent:(id)sender
{
    if (_contactsToInvite.count > 0) {
        
        NSMutableArray* namesArray = [[NSMutableArray alloc] init];
        NSMutableArray* mobilesArray = [[NSMutableArray alloc] init];
        for (Contact* contact in _contactsToInvite) {
            
            [namesArray addObject:contact.name];
            [mobilesArray addObject:contact.mobile];
        }
        
        NSString* allNames = [namesArray componentsJoinedByString:@"♀"];
        NSString* allMobiles = [mobilesArray componentsJoinedByString:@","];
        NSString* circleIds = [[[NSUserDefaults standardUserDefaults] objectForKey:@"circleIds"] componentsJoinedByString:@","];
        
        //先向服务器发送邀请的数据
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_INVITE];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        request.delegate = (id)self;
        request.successSelector = @selector(sendRequestSuccessSelector:);
        [request setValue:circleIds forParameter:@"circleIds"];
        [request setValue:allNames forParameter:@"names"];
        [request setValue:allMobiles forParameter:@"mobiles"];
        [request setValue:_askMessageTextView.text forParameter:@"description"];
        [request asynchronous];
    }
}

- (void)sendRequestSuccessSelector:(NSDictionary *)dict
{
    if ([dict[@"status"] intValue] == 1) {
        
        [Helper showAllTextDialog:_L(@"title_94") inSeconds:3];
        
        
        if (_hasSMSFriends) {
            
            //成功后，调用短信接口
            MFMessageComposeViewController* messageComposeViewController = [[MFMessageComposeViewController alloc] init];
            messageComposeViewController.messageComposeDelegate = (id)self;
            
            NSMutableArray* mobiles = [[NSMutableArray alloc] init];
            for (Contact* contact in _smsFriends) {
                
                [mobiles addObject:contact.mobile];
            }
            messageComposeViewController.body = _L(@"tpl_00");
            messageComposeViewController.recipients = mobiles;
            
            [self.navigationController presentModalViewController:messageComposeViewController animated:true];

        }
        //没有短信好友，就退出
        else {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
    }
    else {
        
        [Helper showAllTextDialog:dict[@"message"] inSeconds:3];
        [Helper showUTF8String:dict[@"error"]];
    }
}

///////////////////////////////////

#pragma mark - UITextView Delegate

- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] > 50) {
        
        textView.text = [textView.text substringToIndex:50];
    }
    
    _askMessageInputCounterLabel.text = [NSString stringWithFormat:_L(@"tpl_49"), 50 - _askMessageTextView.text.length];
}


#pragma mark - SMS Delegate

// 短信发送状态通知协议方法
//
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result)
    {
        case MessageComposeResultCancelled:
            break;
        case MessageComposeResultSent: {
            
            _onBackButtonEventWhenViewDidAppear = true;
        }

            break;
        case MessageComposeResultFailed:
            break;
        default:
            break;
    }

    //必须放在这里，要让case 1内的语句先执行，才能使viewDidAppear获取到正确的值
    [controller dismissModalViewControllerAnimated:true];
}

@end
